
package conection;

import java.awt.Dimension;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.table.DefaultTableModel;
import robocode.rescue.BattleManager;


public class ServerWindow extends javax.swing.JFrame {

  private final int port = 1313;
  
  private boolean isRunning;
  private final AtomicBoolean robotsReady = new AtomicBoolean(false);
  private ServerImpl server;
  private BattleManager battle;
  private ArrayList<TeamStatistics> statistics;
  
  /**
   * Creates new form ServerWindow
   */
  public ServerWindow() {
    initComponents();
    this.setTitle("RoboRescue");
    Dimension screen = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
    this.setLocation(screen.width/2 - this.getWidth()/2, screen.height/2 - this.getHeight()/2);
    
    try {
      server = new ServerImpl(this);
      server.initServer(port);
      battle = new BattleManager(1);
      statistics = new ArrayList<TeamStatistics>();
      isRunning = false;
    } catch (RemoteException ex) {
      Logger.getLogger(ServerWindow.class.getName()).log(Level.SEVERE, null, ex);
    }
  }
  
  public void setRobotsReady() {
    Thread st = new Thread( new Runnable() {
      @Override
      public void run() {
        try {
          Thread.sleep(2000);
          server.start();
        } catch (InterruptedException ex) {
          Logger.getLogger(ServerWindow.class.getName()).log(Level.SEVERE, null, ex);
        }
      }
    });
    st.start();
  }
    
  public void addTeam(String teamName) {
    if (getTeam(teamName) == null) {
      TeamStatistics teamStat = new TeamStatistics(teamName);
      statistics.add(teamStat);
      DefaultTableModel model = (DefaultTableModel) resultsTable.getModel();
      model.addRow(new Object[]{
        teamName,
        0,
        0,
        0
      });
      resultsTable.setModel(model);
    }
    teamASel.addItem(teamName);
    teamBSel.addItem(teamName);
  }
  
  public void remTeam(String teamName) {
    teamASel.removeItem(teamName);
    teamBSel.removeItem(teamName);
  }
  
  public void updateResults() {
    DefaultTableModel model = (DefaultTableModel) resultsTable.getModel();
    model.setNumRows(0);
    for (int i = 0; i < statistics.size(); i++) {
      TeamStatistics ts = statistics.get(i);
      model.addRow(new Object[]{
        ts.getName(),
        ts.getWins(),
        ts.getDraws(),
        ts.getLoses()
      });
    }
    resultsTable.setModel(model);
  }
  
  public TeamStatistics getTeam(String teamName) {
    for (int i = 0; i < statistics.size(); i++) {
      TeamStatistics ts = statistics.get(i);
      if (ts.getName().equals(teamName))
        return ts;
    }
    return null;
  }
  
  /**
   * This method is called from within the constructor to initialize the form.
   * WARNING: Do NOT modify this code. The content of this method is always
   * regenerated by the Form Editor.
   */
  @SuppressWarnings("unchecked")
  // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
  private void initComponents() {

    jPanel1 = new javax.swing.JPanel();
    titleLabel = new javax.swing.JLabel();
    jScrollPane2 = new javax.swing.JScrollPane();
    resultsTable = new javax.swing.JTable();
    teamASel = new javax.swing.JComboBox();
    teamBSel = new javax.swing.JComboBox();
    xLabel = new javax.swing.JLabel();
    startButton = new javax.swing.JButton();
    durationField = new javax.swing.JTextField();
    durationLabel = new javax.swing.JLabel();
    minLabel = new javax.swing.JLabel();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    setBackground(new java.awt.Color(1, 1, 1));
    setPreferredSize(new java.awt.Dimension(600, 400));
    setResizable(false);

    jPanel1.setBackground(new java.awt.Color(1, 1, 1));
    jPanel1.setPreferredSize(new java.awt.Dimension(600, 400));

    titleLabel.setFont(new java.awt.Font("Dialog", 1, 24)); // NOI18N
    titleLabel.setForeground(new java.awt.Color(5, 119, 1));
    titleLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
    titleLabel.setText("RoboRescue");
    titleLabel.setToolTipText("");

    resultsTable.setModel(new javax.swing.table.DefaultTableModel(
      new Object [][] {

      },
      new String [] {
        "Team", "Wins", "Draws", "Loses"
      }
    ) {
      Class[] types = new Class [] {
        java.lang.String.class, java.lang.Integer.class, java.lang.Integer.class, java.lang.Integer.class
      };
      boolean[] canEdit = new boolean [] {
        false, false, false, false
      };

      public Class getColumnClass(int columnIndex) {
        return types [columnIndex];
      }

      public boolean isCellEditable(int rowIndex, int columnIndex) {
        return canEdit [columnIndex];
      }
    });
    resultsTable.setSelectionForeground(new java.awt.Color(254, 254, 254));
    resultsTable.getTableHeader().setReorderingAllowed(false);
    jScrollPane2.setViewportView(resultsTable);
    resultsTable.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_INTERVAL_SELECTION);
    resultsTable.getColumnModel().getColumn(0).setResizable(false);
    resultsTable.getColumnModel().getColumn(1).setResizable(false);
    resultsTable.getColumnModel().getColumn(1).setPreferredWidth(20);
    resultsTable.getColumnModel().getColumn(2).setResizable(false);
    resultsTable.getColumnModel().getColumn(2).setPreferredWidth(20);
    resultsTable.getColumnModel().getColumn(3).setResizable(false);
    resultsTable.getColumnModel().getColumn(3).setPreferredWidth(20);

    xLabel.setForeground(new java.awt.Color(254, 254, 254));
    xLabel.setText("X");

    startButton.setText("Start");
    startButton.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        startButtonActionPerformed(evt);
      }
    });

    durationField.setText("5");

    durationLabel.setForeground(java.awt.Color.lightGray);
    durationLabel.setText("Duração:");

    minLabel.setForeground(java.awt.Color.lightGray);
    minLabel.setText("minutos");

    javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
    jPanel1.setLayout(jPanel1Layout);
    jPanel1Layout.setHorizontalGroup(
      jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(jPanel1Layout.createSequentialGroup()
        .addContainerGap()
        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          .addComponent(titleLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
          .addGroup(jPanel1Layout.createSequentialGroup()
            .addComponent(teamASel, javax.swing.GroupLayout.PREFERRED_SIZE, 272, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(xLabel)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(teamBSel, javax.swing.GroupLayout.PREFERRED_SIZE, 273, javax.swing.GroupLayout.PREFERRED_SIZE))
          .addGroup(jPanel1Layout.createSequentialGroup()
            .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 578, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(0, 0, Short.MAX_VALUE))
          .addGroup(jPanel1Layout.createSequentialGroup()
            .addComponent(durationLabel)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(durationField, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(minLabel)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(startButton, javax.swing.GroupLayout.PREFERRED_SIZE, 157, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(59, 59, 59)))
        .addContainerGap())
    );
    jPanel1Layout.setVerticalGroup(
      jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(jPanel1Layout.createSequentialGroup()
        .addGap(6, 6, 6)
        .addComponent(titleLabel)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 242, javax.swing.GroupLayout.PREFERRED_SIZE)
        .addGap(18, 18, 18)
        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
          .addComponent(teamASel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(teamBSel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(xLabel))
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
          .addComponent(startButton, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(durationField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(durationLabel)
          .addComponent(minLabel))
        .addContainerGap(13, Short.MAX_VALUE))
    );

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(layout.createSequentialGroup()
        .addGap(0, 0, 0)
        .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 602, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    );

    pack();
  }// </editor-fold>//GEN-END:initComponents

  private void startButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_startButtonActionPerformed
    boolean ok;
    String teamA, teamB;
    teamA = (String) teamASel.getSelectedItem();
    teamB = (String) teamBSel.getSelectedItem();
    remTeam(teamA);
    remTeam(teamB);
    ok = server.setup(teamA, teamB);
    if (!ok)
      return;
    this.setVisible(false);
    isRunning = true;
    BattleThread bt = new BattleThread(teamA, teamB);
    //bt.setPriority(Thread.MAX_PRIORITY);
    bt.start();      
  }//GEN-LAST:event_startButtonActionPerformed

  private class BattleThread extends Thread {
    int winner;
    String teamA, teamB;
    BattleThread(String teamA, String teamB) {
      this.teamA = teamA;
      this.teamB = teamB;
    }
    int getWinner() {
      return winner;
    }
    @Override
    public void run() {
      int duration = Integer.valueOf(durationField.getText()) * 60000;
      //BattleManager battle = new BattleManager(1);
      winner = battle.start(teamA, teamB, duration);
      setVisible(true);
      isRunning = false;
      server.stop();
      robotsReady.set(false);
      if (winner == 0) {
        getTeam(teamA).addWin();
        getTeam(teamB).addLose();
      } else if (winner == 1) {
        getTeam(teamA).addLose();
        getTeam(teamB).addWin();
      } else {
        getTeam(teamA).addDraw();
        getTeam(teamB).addDraw();        
      }
      updateResults();
    }
  }
  
  
  /**
   * @param args the command line arguments
   */
  public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
      for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
        if ("Nimbus".equals(info.getName())) {
          javax.swing.UIManager.setLookAndFeel(info.getClassName());
          break;
        }
      }
    } catch (ClassNotFoundException ex) {
      java.util.logging.Logger.getLogger(ServerWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
      java.util.logging.Logger.getLogger(ServerWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
      java.util.logging.Logger.getLogger(ServerWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
      java.util.logging.Logger.getLogger(ServerWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
      public void run() {
        new ServerWindow().setVisible(true);
      }
    });
  }
  // Variables declaration - do not modify//GEN-BEGIN:variables
  private javax.swing.JTextField durationField;
  private javax.swing.JLabel durationLabel;
  private javax.swing.JPanel jPanel1;
  private javax.swing.JScrollPane jScrollPane2;
  private javax.swing.JLabel minLabel;
  private javax.swing.JTable resultsTable;
  private javax.swing.JButton startButton;
  private javax.swing.JComboBox teamASel;
  private javax.swing.JComboBox teamBSel;
  private javax.swing.JLabel titleLabel;
  private javax.swing.JLabel xLabel;
  // End of variables declaration//GEN-END:variables
}
